package com.example.filedownload;

import com.example.filedownload.filedownload.DownloadManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.io.IOException;

@RestController
public class DownloadController {

    @GetMapping("/getFileLocation")
    public String getFileLocation(String url) {
        String downloadPath = Util.getDefaultDownloadPath();
        String fileName = Util.getFileName(url);
        return downloadPath + fileName;
    }

    @GetMapping("/getDownloadSize")
    public int getDownloadSize() {
        // 获取已经下载的文件大小
        if(!CacheEntity.getSingleTon().getIsDownload()){
            return 0;
        }
       float f= 100*CacheEntity.getSingleTon().getDownloadSize().get()/CacheEntity.getSingleTon().getTotalSize();
        return (int)f;
    }

    @GetMapping("beginDownload")
    public boolean beginDownload(@RequestParam String url) {
        //环境初始化
        long size;
        try {
            size = Util.getFileLength(url);
            if (size == 0) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        CacheEntity.getSingleTon().setFileUrl(url);
        CacheEntity.getSingleTon().setTotalSize(size);
        CacheEntity.getSingleTon().setIsDownload(true);
        String downloadPath = Util.getDefaultDownloadPath();
        String fileName = Util.getFileName(url);
        String savePath = downloadPath + fileName;
        CacheEntity.getSingleTon().setSavePath(savePath);
        String tmpPath = fileName.split("\\.")[0];
        CacheEntity.getSingleTon().setTmpFilePath(tmpPath);
        CacheEntity.getSingleTon().setIsSuccess(false);
        DownloadManager downloadManager = new DownloadManager(savePath, 15, url);
        //开始下载文件
        downloadManager.action();
        return true;
    }
    @GetMapping("/canDownload")
    public boolean canDownload(){
        // 先判断是否有别的在下载
        if(CacheEntity.getSingleTon().getIsDownload()==true){
            return false;
        }
        return true;
    }

    @GetMapping("/exit")
    public void exit(){
        System.exit(0);
    }

}
